<script setup lang='ts'>
import { ref, onMounted, reactive } from 'vue';
import { getServer } from '@/api/server';
import { editMirror, delMirror, getUserMirrorList, addVirtualMirror } from '@/api/mirror';
import { uploadFile, getFileList } from '@/api/message';
import { message } from '@/utils/message';
import { mainUrl } from "@/api/utils";
import { getServerPlan } from '@/api/server';

const serverList = ref([]);
const mirrorList = ref([]);
const dialogVisible = ref(false);
const selectedFileName = ref(null);
const planlist = ref([]);
const editOr = ref(false);
const loading = ref(false)
const form = reactive({
  name: '',
  show_name: '',
  description: '',
  server_type: 'hyperV',
  plan_id: '',
  image_ico: '',
  server_id: '',
  path: ''
});
const netform = reactive({
  type: "",
  container_id: "",
  server_port: "",
  container_port: "",
  domain: "",
  floating_ip: ""
});
const network_list = [
  {
    value: "nginx",
    name: "建站服务"
  },
  {
    value: "port_forward",
    name: "自定义端口"
  },
  {
    value: "floating_ip",
    name: "独立ip"
  }
];
onMounted(() => {
  getList()
});

const getList = () => {
  getServer(1, 100, '', 'hyperV').then((res) => {
    serverList.value = res.data.data.map(item => ({ server_id: item.server_id, name: item.name }));
    const promises = serverList.value.map(item =>
      getUserMirrorList({ server_id: item.server_id, count: 10, page: 1, key: '' })
        .then(res => ({
          name: item.name,
          server_id: item.server_id,
          mirror_list: res.data.data,
          total: res.data.count,
          page: ref(1)
        }))
    );
    Promise.all(promises).then(results => {
      mirrorList.value = results;
      mirrorList.value.sort((a, b) => a.name - b.name);
    });
  });
};
const toLoad = async (data) => {
  console.log(data, '信息');
  dialogVisible.value = true;
  editOr.value = false;
  envList.value = [];
  Object.keys(form).forEach(key => {
    form[key] = null;
  });
  form.server_id = data;
  nowserver_id.value = data;
  let res = await getServerPlan({ server_id: data });
  planlist.value = res.data.data.map(item => {
    return {
      name: item.name,
      id: item.plan_id,
    }
  });
}
const onFileSelected = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFileName.value = file.name; // 显示文件名
    uploadFile({ file: file }).then((res) => {
      if (res.data.code == 200) {
        message('上传成功', { type: 'success' });
        selectedFileName.value = null;
        console.log('/v1/attachment/get_attachment?aid=' + res.data.data.attachment_id);
        form.image_ico = '/v1/attachment/get_attachment?aid=' + res.data.data.attachment_id
      }
    })
  } else {
    selectedFileName.value = null; // 如果用户取消选择，清空文件名
  }
}
const delProt = (index, data) => {
  prot_data.value.splice(index, 1);
}
//上传镜像
const uploadImage = async () => {
  if (editOr.value == true) {
    form.image_id = form.id;
    delete form.id;
    let res = await editMirror(form);
    if (res.data.code == 200) {
      dialogVisible.value = false;
      message('编辑成功', { type: 'success' });
      mirrorList.value = []
      getList()
    }
  } else {
    let res = await addVirtualMirror(form);
    if (res.data.code == 200) {
      dialogVisible.value = false;
      message('上传成功', { type: 'success' });
      mirrorList.value = []
      getList()
    }
  }

}
//编辑镜像
const handleEdit = async (data) => {
  let res = await getServerPlan(data);
  planlist.value = res.data.data.map(item => {
    return {
      name: item.name,
      id: item.plan_id,
    }
  });
  editOr.value = true;
  dialogVisible.value = true;
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      form[key] = data[key];
    }
  }
  if (data.proxy != null) {
    prot_data.value = JSON.parse(data.proxy);
  } else {
    prot_data.value = [];
  }
}
//删除镜像
const deleteMirror = (data) => {
  delMirror({ server_id: data.server_id, image_id: data.id }).then((res) => {
    if (res.data.code == 200) {
      message('删除成功', { type: 'success' });
      mirrorList.value = []
      getList()
    }
  })
}

//镜像环境
const envItem = reactive({
  key: '',
  value: ''
});
const envList = ref([]);
const envSwitch = ref(false);
const addenv = (data) => {
  envList.value.push({ ...data });
  message('添加成功', { type: 'success' });
  envSwitch.value = false;
  envItem.key = ''
  envItem.value = '',
    console.log('envList', envList.value)
}
const delenv = (index) => {
  envList.value.splice(index, 1);
  message('删除成功', { type: 'success' });
}
//复制
//当前服务器
const nowserver_id = ref('')
const copytext = ref({});
const copyit = async () => {
  copytext.value = JSON.parse(JSON.stringify(form));
  message('复制成功', { type: 'success' });
  await navigator.clipboard.writeText(JSON.stringify(copytext.value));
}
const getit = async () => {
  try {
    const text = await navigator.clipboard.readText();
    console.log('从剪贴板读取的文本:', text);
    Object.keys(JSON.parse(text)).forEach(key => {
      form[key] = JSON.parse(text)[key];
    });
    form.server_id = nowserver_id.value
    message('粘贴成功', { type: 'success' })
    return text;
  } catch (err) {
    message('无法读取剪贴板内容,请检查获取到的格式', { type: 'error' })
  }
}
const handleCurrentPageChange = async (newPage, id, index, item) => {
  console.log('newPage', newPage)
  item.page = newPage;
  getUserMirrorList({ server_id: id, count: 10, page: newPage, key: '' }).then(res => {
    console.log('xin服务器的镜像', res.data.data);
    console.log('要修改的数据', mirrorList.value[index].mirror_list)
    mirrorList.value[index].mirror_list = res.data.data;
  })
};
//选择图片
const picSwitch = ref(false);
const picPagin = reactive({
  count: 50,
  page: 1,
  key: '',
  user_type: 1
});
const picList = ref([]);
const total = ref(10);
const getpicList = () => {
  getFileList(picPagin).then(res => {
    console.log('获取到的图片', res.data.data);
    picList.value = res.data.data;
    total.value = res.data.count

  })
}
const currentIndex = ref(null);
const selectImage = (index, data) => {
  currentIndex.value = index;
  console.log('当前选择的图片', data);

}
const CurrentPageChange = async newPage => {
  picPagin.page = newPage;
  getpicList()
};
const PageSizeChange = async newSize => {
  picPagin.count = newSize;
  getpicList()
};
const tochoose = () => {
  if (currentIndex.value != null) {
    form.image_ico = `/v1/attachment/get_attachment?aid=${picList.value[currentIndex.value].attachment_id}`;
    picSwitch.value = false;
  }
}
</script>

<template>
  <div v-loading="loading">
    <div v-for="(item, index) in mirrorList">
      <span style="font-size: 15px;padding-bottom: 5px">{{ item.name }}</span>
      <el-button type="primary" plain style="margin: 10px" @click="toLoad(item.server_id)">新增镜像</el-button>
      <el-table class="table_el" :data="item.mirror_list" style="width: auto">
        <el-table-column label="镜像ID" prop="id" width="100" />
        <el-table-column label="镜像名称" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="展示名称" prop="show_name" show-overflow-tooltip />
        <el-table-column label="图标" show-overflow-tooltip>
          <template #default="scope">
            <img :src="mainUrl + scope.row.image_ico" style="width: 30px;height: 30px;" /></img>
          </template>
        </el-table-column>
        <el-table-column label="描述" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.description }}
          </template>
        </el-table-column>
        <el-table-column label="状态" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="scope.row.state == 0 ? 'primary' : scope.row.state == 1 ? 'success' : 'danger'"> {{
              scope.row.state == 0 ? '上传中' : scope.row.state == 1 ? '上传成功' : '上传失败' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" show-overflow-tooltip />
        <el-table-column width="200" label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" plain @click="deleteMirror(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next" :total="item.total" :current-page="item.page" :page-size="10"
        @update:current-page="(newPage) => handleCurrentPageChange(newPage, item.server_id, index, item)" />
    </div>
    <el-dialog v-model="dialogVisible" :title="editOr ? '编辑镜像' : '上传镜像'" width="50%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="镜像名称">
          <el-input v-model="form.name" placeholder="请输入镜像名称" />
        </el-form-item>
        <el-form-item label="文件路径">
          <el-input v-model="form.path" placeholder="请输入镜像文件路径" :readonly="editOr" />
        </el-form-item>
        <el-form-item label="展示名称">
          <el-input v-model="form.show_name" />
        </el-form-item>
        <el-form-item label="图标">
          <img v-if="form.image_ico" style="width: 30px;height:30px" :src="mainUrl + form.image_ico" /></img>
          <el-button class="btn" style="margin:0 10px" @click="$refs.fileInput.click()">上传附件</el-button>
          <input ref="fileInput" type="file" style="display:none" @change="onFileSelected" />
          <span v-if="selectedFileName" class="file-name">{{ selectedFileName }}</span>
          <el-button @click="picSwitch = true; getpicList()">从素材库选择</el-button>
        </el-form-item>
        <el-form-item label="套餐">
          <el-select v-model="form.plan_id" placeholder="请选择套餐" size="large" style="width: 240px">
            <el-option v-for="item in planlist" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="镜像描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="getit">一键粘贴内容</el-button>
          <el-button @click="copyit">一键复制内容</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadImage">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="picSwitch" title="素材库" width="70vw" draggable overflow>
      <el-input v-model="picPagin.key" placeholder="请输入搜索内容" style="width: 30%;margin-left: 20px"
        @blur="getpicList()" />
      <div class="piclist">
        <div v-for="(item, index) in picList" :key="index" class="icon" :class="{ choose: currentIndex === index }"
          @click="selectImage(index, item)">
          <img :src="`${mainUrl}/v1/attachment/get_attachment?aid=${item.attachment_id}`" /></img>
          <el-tooltip class="box-item" effect="dark" :content="item.title" placement="bottom">
            <div class="tit">{{ item.title.slice(0, 8) }}</div>
          </el-tooltip>
        </div>
      </div>
      <el-pagination background layout="prev, pager, next,sizes" :total="total" :current-page="picPagin.page"
        :page-size="picPagin.count" :page-sizes="[10, 20, 50, 100]" style="margin-left: 20px"
        @update:current-page="CurrentPageChange" @update:page-size="PageSizeChange" />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="picSwitch = false">关闭</el-button>
          <el-button type="primary" @click="tochoose">选择</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<style lang='scss'>
.el-popper {
  max-width: 300px !important;
}

.piclist {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .icon {
    width: 70px;
    margin: 10px;
    padding: 5px;
    border-radius: 5px;

    &:hover {
      cursor: pointer;
      box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.1);
    }

  }

  img {
    width: 45px;
    height: 45px;
    margin: 0 auto;
  }

  .tit {
    font-size: 12px;
    text-align: center;
    width: 100%;
    overflow: hidden;
  }

  .choose {
    box-shadow: 0 0 10px 5px rgba(0, 255, 0, 0.3);
  }

}
</style>
